package org.xiaozhou.chatgptcativen.domain.security.service;

import org.apache.shiro.web.filter.AccessControlFilter;
import org.slf4j.Logger;
import org.xiaozhou.chatgptcativen.domain.security.model.vo.JwtToken;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class JwtFilter extends AccessControlFilter {

    private Logger logger = org.slf4j.LoggerFactory.getLogger(JwtFilter.class);
    @Override
    protected boolean isAccessAllowed(ServletRequest servletRequest, ServletResponse servletResponse, Object o) throws Exception {
        return false;
    }

    @Override
    protected boolean onAccessDenied(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        String token = httpServletRequest.getParameter("token");
        JwtToken jwtToken = new JwtToken(token);
        try {
            getSubject(servletRequest, servletResponse).login(jwtToken);
        }catch (Exception e){
            logger.error("鉴权认证失败", e);
            onLoginFail(servletResponse);
        }
        return false;
    }

    private void onLoginFail(ServletResponse servletResponse) throws IOException {
        HttpServletResponse httpResponse = (HttpServletResponse) servletResponse;
        httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        httpResponse.getWriter().write("Auth Err!");
    }
}
